package juc.blockqueue.linkedtransferqueue;

/**
 * @ClassName RealTimeMessagingSystem
 * @PackageName juc.blockqueue.linkedtransferqueue
 * @projectName myThread
 * @Description 2. 实时消息传递系统
 * @Author games
 * @Date 2025/9/4 下午4:01
 * @Version 1.0
 */
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.TransferQueue;

class Message {
    private final String content;
    private final long timestamp;

    public Message(String content) {
        this.content = content;
        this.timestamp = System.currentTimeMillis();
    }

    public String getContent() { return content; }
    public long getTimestamp() { return timestamp; }

    @Override
    public String toString() {
        return "Message{content='" + content + "', timestamp=" + timestamp + "}";
    }
}

public class RealTimeMessagingSystem {
    public static void main(String[] args) {
        TransferQueue<Message> messageQueue = new LinkedTransferQueue<>();

        // 消息发送者
        Thread sender = new Thread(() -> {
            try {
                // 尝试直接传递消息
                Message urgentMessage = new Message("紧急消息");
                if (messageQueue.tryTransfer(urgentMessage)) {
                    System.out.println("紧急消息已直接传递: " + urgentMessage);
                } else {
                    messageQueue.put(urgentMessage);
                    System.out.println("紧急消息已加入队列: " + urgentMessage);
                }

                // 普通消息
                Thread.sleep(1000);
                Message normalMessage = new Message("普通消息");
                messageQueue.put(normalMessage);
                System.out.println("普通消息已加入队列: " + normalMessage);

            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        // 消息接收者
        Thread receiver = new Thread(() -> {
            try {
                while (true) {
                    // 检查是否有等待的消息
                    if (messageQueue.hasWaitingConsumer()) {
                        System.out.println("当前有 " + messageQueue.getWaitingConsumerCount() + " 个消费者等待");
                    }

                    Message message = messageQueue.take();
                    System.out.println("接收到消息: " + message);
                    Thread.sleep(2000); // 模拟处理时间
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        receiver.start();
        sender.start();
    }
}
